package oj;

public class LC79 {
    public boolean exist(char[][] board, String word) {
        int m=board.length;
        int n=board[0].length;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(dfs(board,word,i,j,0)){
                    return true;
                }
            }
        }
        return false;
    }

    int[] dx=new int[]{0,0,1,-1};
    int[] dy=new int[]{1,-1,0,0};
    private boolean dfs(char[][] board,String s,int i,int j,int k){
        int m=board.length;
        int n=board[0].length;
        if(board[i][j]!=s.charAt(k)){
            return false;
        }else if(k==s.length()-1){
            return true;
        }
        char c=board[i][j];
        board[i][j]='.';
        for(int z=0;z<4;z++){
            int a=i+dx[z];
            int b=j+dy[z];
            if(a<0 || a>=m || b<0 || b>=n || board[a][b]=='.'){
                continue;
            }
            if(dfs(board,s,a,b,k+1)) return true;
        }
        board[i][j]=c;
        return false;
    }
}
